<template>

    <div style="width: 100%; display: flex; flex-direction: column;">
        <!-- 上面的内容，靠右对齐 -->
        <div style="display: flex; justify-content: flex-end;">
            <el-button type="primary" :icon="Plus" @click="GetDialog">添加</el-button>
        </div>
        <!-- 下面的内容，靠左对齐 -->
        <div style="display: flex; justify-content: flex-start; margin: 10px;">
            <el-input v-model="query.sn" style="width: 200px; margin-right: 10px;" placeholder="请输入SN" clearable />
            <el-input v-model="query.deviceTypeName" style="width: 200px; margin-right: 10px;" placeholder="请输入设备类型"
                clearable />
            <el-input v-model="query.imei" style="width: 200px; margin-right: 10px;" placeholder="请输入IMEI" clearable />
            <el-input v-model="query.customerName" style="width: 200px; margin-right: 10px;" placeholder="请输入客户名称"
                clearable />
            <el-button type="primary" :icon="Search" @click="GetData">查询</el-button>
        </div>
    </div>
    <!-- :span-method="objectSpanMethod" -->
    <el-table :data="tableData" row-key="id" default-expand-all ref="tableRef" :border="true"
        :show-overflow-tooltip="true" empty-text="暂无数据" max-height="650px">
        <el-table-column type="selection" prop="id" />
        <el-table-column fixed prop="createDate" label="创建时间" />
        <el-table-column prop="sn" label="设备序列号" />
        <el-table-column prop="imei" label="IMEI" />
        <el-table-column prop="deviceTypeName" label="设备类型" />
        <el-table-column prop="customerName" label="客户名称" />
        <el-table-column fixed="right" label="操作" min-width="80">
            <template #default="{ row }">
                <el-button link type="primary" size="small" @click="GetDialog2(row, 1)">
                    IMEI录入
                </el-button>
                <el-button link type="primary" size="small" @click="GetDialog2(row, 2)">
                    查看
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination style="margin-top: 20px;" v-model:current-page="query.pageNumber" v-model:page-size="query.pageSize" :page-sizes="[10, 30, 100]"
        size="default" :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @update:page-size="handleSizeChange" @update:current-page="handleCurrentChange" />

    <el-dialog v-model="dialogFormVisible" title="添加设备类型" width="500" @close="dialogclose" :close-on-click-modal=false>
        <el-form style="max-width: 600px" label-width="auto" :model="submitData" :rules="rules" ref="ruleFormRef"
            class="demo-ruleForm">
            <el-form-item label="客户名称" prop="customerId">
                <el-select v-model="submitData.customerId" filterable placeholder="请选择客户">
                    <el-option v-for="item in selectData.cusData" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="设备类型" prop="deviceTypeId">
                <el-select v-model="submitData.deviceTypeId" filterable placeholder="请选择设备类型">
                    <el-option v-for="item in selectData.devData" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="生成条数">
                <el-input-number v-model="submitData.produceSun" :min="1" :max="1000" />
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="submitData.description" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible2" title="设备信息" width="500" @close="dialogclose" :close-on-click-modal=false>
        <el-form style="max-width: 600px" label-width="auto" :model="submitData2" :rules="rules" ref="ruleFormRef"
            class="demo-ruleForm">
            <el-form-item label="设备序列号">
                <el-text class="mx-1">{{ SnNubmer }}</el-text>
            </el-form-item>
            <el-form-item label="IMEI" prop="imei">
                <el-input v-model="submitData2.imei" placeholder="请输入IMEI" clearable v-if="textType" />
                <el-text v-else class="mx-1">{{ submitData2.imei }}</el-text>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="submitData2.description" v-if="textType" />
                <el-text v-else class="mx-1">{{ submitData2.description }}</el-text>
            </el-form-item>
            <el-card style="max-width: 480px" v-if="isCodeImage">
                <template #header>二维码信息</template>
                <div style="text-align: center;">
                    <img :src="qrImage" ref="imageElement" alt="QRCode with Text" />
                </div>
            </el-card>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取消</el-button>

                <el-dropdown placement="bottom-start" v-if="isCodeImage">
                    <el-button style="margin-left: 10px;margin-right: 10px;">打印/导出</el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="printImage"> <el-icon>
                                    <Printer />
                                </el-icon> 打印</el-dropdown-item>
                            <el-dropdown-item @click="downloadImage"> <el-icon>
                                    <Download />
                                </el-icon>导出</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>

                <el-button v-if="textType" type="primary" @click="submitForm2(ruleFormRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { Plus, Search, Printer, Download } from "@element-plus/icons-vue";
import { QueryDeviceListApi, CreaeDeviceApi, CreateImeiApi } from "../../api/device";
import type { deviceSn } from "../../api/device";
import type { Iquerydevice, ICreateImei } from '../../api/device'
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus'
import { KeyValueApi } from '../../api/index'
import QRCode from 'qrcode';
import printJS from 'print-js';
const ruleFormRef = ref<FormInstance>();
const query = ref<Iquerydevice>({
    sn: '',
    deviceTypeName: '',
    customerName: '',
    imei: '',
    pageNumber: 1,
    pageSize: 10
})
const tableData = ref<any>();
const dialogFormVisible = ref(false)
const dialogFormVisible2 = ref(false)
const total = ref<Number>();
const selectData = ref<any>({
    cusData: [],
    devData: []
})
const submitData = ref<deviceSn>({
    customerId: "",
    deviceTypeId: "",
    produceSun: 1,
    description: ""
})
const submitData2 = ref<ICreateImei>({
    imei: '',
    deviceId: '',
    description: ''
})
const SnNubmer = ref<String>();

const rules = {
    customerId: [
        { required: true, message: '客户选择不能为空', trigger: 'change' }
    ],
    deviceTypeId: [
        { required: true, message: '设备类型选择不能为空', trigger: 'change' }
    ],
    imei: [
        { required: true, message: 'IMEI不能为空', trigger: 'blur' }
    ]
};

const handleSizeChange = (val: number) => {
    query.value.pageSize = val
    GetData();
}
const handleCurrentChange = (val: number) => {
    query.value.pageNumber = val
    GetData();
}

const GetData = async () => {
    let res = await QueryDeviceListApi(query.value);
    tableData.value = res.data.items
    total.value = res.data.count
}


const GetDialog = async () => {
    let res1 = await KeyValueApi('Customer');
    let res2 = await KeyValueApi('DeviceType');
    console.log(res1, res2);
    selectData.value.cusData = res1.data.data
    selectData.value.devData = res2.data.data;
    dialogFormVisible.value = true
}

const textType = ref<boolean>(false);
const GetDialog2 = async (val: any, type: Number) => {
    if ((val.imei == '' || val.imei == null) && type == 2) {
        ElMessage({
            message: "请先录入IMEI信息",
            type: 'warning',
        })
        return;
    }
    SnNubmer.value = val.sn
    submitData2.value.deviceId = val.id
    submitData2.value.imei = val.imei
    submitData2.value.description = val.description
    dialogFormVisible2.value = true
    if (type == 1) {
        textType.value = true;
    } else {
        textType.value = false;
        isCodeImage.value = true;
        await createQrcode({ sn: val.sn, imei: val.imei });
    }
}


const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    // 使用 Promise 包裹 validate 函数，确保可以使用 await
    const valid = await new Promise<boolean>((resolve) => {
        formEl.validate((valid) => {
            if (valid) {
                resolve(true);
            } else {
                resolve(false);
            }
        });
    });
    if (valid) {
        let res = await CreaeDeviceApi(submitData.value);
        if (res.statusCode == 200) {
            dialogFormVisible.value = false
            GetData()
            ElMessage({
                message: res.message,
                type: 'success',
            })
        }
    }
}

const isCodeImage = ref(false);
const submitForm2 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    // 使用 Promise 包裹 validate 函数，确保可以使用 await
    const valid = await new Promise<boolean>((resolve) => {
        formEl.validate((valid) => {
            if (valid) {
                resolve(true);
            } else {
                resolve(false);
            }
        });
    });
    if (valid) {
        let res = await CreateImeiApi(submitData2.value);
        if (res.statusCode == 200) {
            // dialogFormVisible2.value = false
            isCodeImage.value = true;
            let from = {
                sn: SnNubmer.value,
                imei: submitData2.value.imei
            }
            ElMessage({
                message: res.message,
                type: 'success',
            })
            await createQrcode(from);

        }
    }
}

const qrText = ref('');
const qrImage = ref('');
const createQrcode = async (row: any) => {
    if (row.imei == '' || row.imei == null) {
        ElMessage({
            message: "请先录入IMEI信息",
            type: 'warning',
        })
        return;
    }
    qrText.value = "SN:" + row.sn + ',' + "IMEI:" + row.imei
    await nextTick();
    try {
        const qrcodeCanvas = document.createElement('canvas');
        await QRCode.toCanvas(qrcodeCanvas, qrText.value);
        // Step 2: 创建新的 Canvas 合成二维码和文本
        const finalCanvas = document.createElement('canvas');
        const ctx = finalCanvas.getContext('2d');
        if (!ctx) {
            console.error("无法获取 canvas 的 2d 上下文！");
            return;
        }
        // 获取二维码的宽高
        const qrWidth = qrcodeCanvas.width;
        const qrHeight = qrcodeCanvas.height;
        // Step 3: 设置最终 Canvas 尺寸
        finalCanvas.width = qrWidth;
        finalCanvas.height = qrHeight; // 加上文本高度
        // Step 4: 将二维码绘制到新 Canvas
        ctx.drawImage(qrcodeCanvas, 0, 0);
        // Step 5: 绘制文本
        ctx.font = '12rpx Arial';
        ctx.fillStyle = '#000';
        ctx.textAlign = 'center';
        ctx.fillText(row.sn, qrWidth / 2, qrHeight-5); // 文本位置在二维码下方
        // Step 6: 将合成后的 Canvas 转换为图像 URL
        qrImage.value = finalCanvas.toDataURL('image/png');
    } catch (error) {
        console.error('生成二维码失败:', error);
    }

}

const printImage = () => {
    printJS({
        printable: qrImage.value, // 图片的URL
        type: 'image', // 指定打印类型为图片
        showModal: true, // 可选，显示加载进度条
        style: `
          @media print {
            body {
              margin: 0;
              padding: 0;
              width: 100%;
            }
            img {
              width: 100%; 
              height: 100%;
              margin-top: -50px;
              display: block;
            }
            /* 隐藏任何可能的额外内容 */
            .print-header, .print-footer {
              display: none;
            }
          }
        `
    });
}


const dialogclose = () => {
    SnNubmer.value = '';
    isCodeImage.value = false;
    submitData2.value = {
        imei: '',
        deviceId: '',
        description: ''
    };
    submitData.value = {
        customerId: "",
        deviceTypeId: "",
        produceSun: 1,
        description: ""
    }
    GetData();
}

const imageElement = ref();
// 下载图片的函数
const downloadImage = () => {
    const imgElement = imageElement.value; // 获取图片元素

    // 创建一个临时的 <a> 标签
    const link = document.createElement('a');
    link.href = imgElement.src; // 设置图片 URL
    link.download = SnNubmer.value + '.png'; // 设置下载文件名
    document.body.appendChild(link);

    // 触发下载
    link.click();

    // 移除 <a> 标签
    document.body.removeChild(link);
};


onMounted(() => {
    GetData();
})
</script>
<style scoped>
:deep(.el-textarea__inner) {
    outline: none;
    border: none;
    resize: none;
    box-shadow: none;
    background: #F8F8F8;
}

.firstdiv {}

.row-div h2 {
    margin-left: 10px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    /* 让内部元素左右对齐并分开 */
}

.card-span2 {
    font-size: 12px;
}

.el-descriptions {
    margin-top: 20px;
}

.cell-item {
    display: flex;
    align-items: center;
}

.margin-top {
    margin-top: 20px;
}

.pagination-with-border {
    border: 1px solid #e6ebf5;
    border-top: none;
    overflow: hidden;
    padding: 10px;
}
</style>